/*
 * Copyright (c) 2022-2022 Huawei Technologies Co., Ltd. All rights reserved.
 * Copyright (c) 2022-2022 Huawei Device Co., Ltd. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this list of
 * conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list
 * of conditions and the following disclaimer in the documentation and/or other materials
 * provided with the distribution.
 *
 * 3. Neither the name of the copyright holder nor the names of its contributors may be used
 * to endorse or promote products derived from this software without specific prior written
 * permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
#include "It_posix_container.h"
#include <netinet/in.h>
#include <string.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <net/route.h>

#define STACK_SIZE (1024 * 1024)    /* Stack size for cloned child */
#define CHILD_FUNC_ARG (0x2088)
#define THREAD_STACK_SIZE 2048
#define NETMASK "255.255.255.0"
#define GW "192.168.100.1"
#define IFNAME "veth0"
#define SERVER_IP "192.168.100.6"
#define SERVER_PORT 8005
#define PEER_IP "192.168.100.5"
#define SERVER_MSG "===Hi, I'm Server.==="
#define PEER_MSG "===Hi, I'm Peer.==="
#define TRY_COUNT 5

static int TryResetNetaddr(char *ifname, char *ip, char *netmask, char *gw) {
    int ret;
    int fd;
    struct ifreq ifr;
    struct rtentry rt;

    fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
    strncpy(ifr.ifr_name, ifname, IFNAMSIZ);
    ifr.ifr_addr.sa_family = AF_INET;

    inet_pton(AF_INET, netmask, ifr.ifr_addr.sa_data + 2);
    ret = ioctl(fd, SIOCSIFNETMASK, &ifr);

    if (ret == 0) {
        inet_pton(AF_INET, ip, ifr.ifr_addr.sa_data + 2);
        ret = ioctl(fd, SIOCSIFADDR, &ifr);
    }

    if (ret == 0) {
        struct sockaddr_in* addr = (struct sockaddr_in*)(&rt.rt_gateway);
        addr->sin_family = AF_INET;
        addr->sin_addr.s_addr = inet_addr(GW);
        rt.rt_flags = RTF_GATEWAY;
        ret = ioctl(fd, SIOCADDRT, &rt);
    }

    (void)close(fd);

    return ret;
}

static int ResetNetaddr(char *ifname, char *ip, char *netmask, char *gw) {
    int ret;
    int try_count = TRY_COUNT;

    while(try_count--) {
        ret = TryResetNetaddr(ifname, ip, netmask, gw);
        if (ret == 0) {
            break;
        }
        sleep(1);
    }

    return ret;
}

static int TcpClient(void) {
    int ret = 0;
    int peer;
    int try_count = TRY_COUNT;
    char recv_data[sizeof(SERVER_MSG)];
    struct sockaddr_in server_addr;

    peer = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    ICUNIT_ASSERT_NOT_EQUAL(peer, -1, peer);

    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr(SERVER_IP);
    server_addr.sin_port = htons(SERVER_PORT);
    (void)memset(&(server_addr.sin_zero), 0, sizeof(server_addr.sin_zero));

    do {
        sleep(1);
        ret = connect(peer, (const struct sockaddr *)&server_addr, sizeof(struct sockaddr));
    } while(ret !=0 && (try_count--));
    ICUNIT_ASSERT_NOT_EQUAL(ret, -1, ret);

    ret = send(peer, PEER_MSG, sizeof(PEER_MSG), 0);
    ICUNIT_ASSERT_NOT_EQUAL(ret, -1, ret);

    ret = recv(peer, recv_data, sizeof(recv_data), 0);
    ICUNIT_ASSERT_NOT_EQUAL(ret, -1, ret);

    ret = strcmp(recv_data, SERVER_MSG);
    ICUNIT_ASSERT_EQUAL(ret, 0, ret);

    (void)close(peer);

    return 0;
}

static int TcpServer(void)
{
    int ret = 0;
    int server;
    int peer;
    char recv_data[sizeof(PEER_MSG)];
    struct sockaddr_in server_addr;
    socklen_t client_addr_len = sizeof(struct sockaddr);

    server = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    ICUNIT_ASSERT_NOT_EQUAL(server, -1, server);

    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr(SERVER_IP);
    server_addr.sin_port = htons(SERVER_PORT);
    (void)memset(&(server_addr.sin_zero), 0, sizeof(server_addr.sin_zero));

    ret = bind(server, (struct sockaddr *)&server_addr, sizeof(struct sockaddr));
    ICUNIT_ASSERT_EQUAL(ret, 0, ret);

    ret = listen(server, 1);
    ICUNIT_ASSERT_NOT_EQUAL(ret, -1, ret);

    peer = accept(server, NULL, 0);
    ICUNIT_ASSERT_NOT_EQUAL(peer, -1, peer);

    (void)close(server);

    ret = recv(peer, recv_data, sizeof(recv_data), 0);
    ICUNIT_ASSERT_NOT_EQUAL(ret, -1, ret);

    ret = strcmp(recv_data, PEER_MSG);
    ICUNIT_ASSERT_EQUAL(ret, 0, ret);

    ret = send(peer, SERVER_MSG, sizeof(SERVER_MSG), 0);
    ICUNIT_ASSERT_NOT_EQUAL(ret, -1, ret);

    (void)close(peer);

    return 0;
}

static void *TcpClientThread(void *arg)
{
    int ret;

    ret = ResetNetaddr(IFNAME, PEER_IP, NETMASK, GW);

    if (ret == 0) {
        ret = TcpClient();
    }

    return (void*)(intptr_t)ret;
}

static int childFunc(void *arg) {
    int ret = ret = ResetNetaddr(IFNAME, SERVER_IP, NETMASK, GW);
    ICUNIT_ASSERT_EQUAL(ret, 0, ret);

    return TcpServer();
}

static UINT32 TestCase(VOID)
{
    int ret = 0;
    int status;
    void *tret = NULL;
    pthread_t srv;
    pthread_attr_t attr;

    char *stack;
    char *stackTop;
    stack = (char*)mmap(NULL, STACK_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0);
    stackTop = stack + STACK_SIZE;

    int arg = CHILD_FUNC_ARG;
    int pid = clone(childFunc, stackTop, SIGCHLD | CLONE_NEWNET, &arg);

    ret = pthread_attr_init(&attr);
    ICUNIT_ASSERT_EQUAL(ret, 0, ret);

    ret = pthread_create(&srv, &attr, TcpClientThread, NULL);
    ICUNIT_ASSERT_EQUAL(ret, 0, ret);

    ret = pthread_join(srv, &tret);
    ICUNIT_ASSERT_EQUAL(ret, 0, ret);

    ret = pthread_attr_destroy(&attr);
    ICUNIT_ASSERT_EQUAL(ret, 0, ret);

    ret = waitpid(pid, &status, 0);
    ICUNIT_ASSERT_EQUAL(ret, pid, ret);

    int exitCode = WEXITSTATUS(status);
    ICUNIT_ASSERT_EQUAL(exitCode, 0, exitCode);

    return 0;
}

VOID ItPosixContainerNet009(void)
{
    TEST_ADD_CASE("IT_POSIX_CONTAINER_NET_009", TestCase, TEST_POSIX, TEST_CONTAINER, TEST_LEVEL0, TEST_FUNCTION);
}
